package com.etennis.controller;

import com.etennis.constants.AppHttpCodeEnum;
import com.etennis.pojos.ResponseResult;
import com.etennis.pojos.dto.LoginDTO;
import com.etennis.pojos.entity.Club;
import com.etennis.pojos.vo.app.ClubVO;
import com.etennis.pojos.vo.web.ClubLoginVO;
import com.etennis.security.LoginClubDetails;
import com.etennis.utils.BeanCopyUtils;
import com.etennis.utils.JwtUtil;
import com.etennis.utils.RedisCache;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @program: ETennis
 * @ClassName: LoginController
 * @description:
 * @author: kai
 * @create: 2024-10-17 22:43
 */
@RestController
@RequestMapping("web")
@Api(tags = "网页端-登录接口")
public class LoginController {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @PostMapping("/login")
    public ResponseResult<ClubLoginVO> webLogin(@RequestBody LoginDTO userLoginDTO){
        return login(userLoginDTO);
    }
    public ResponseResult<ClubLoginVO> login(LoginDTO user) {
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(user.getAccount(),user.getPassword());
        Authentication authentication=authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authentication)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR,"login error");
        }
        LoginClubDetails loginUser = (LoginClubDetails) authentication.getPrincipal();
        String clubId = loginUser.getClub().getAccount();
        String jwt= JwtUtil.createJWT(clubId);
        redisCache.setCacheObject(clubId,loginUser);
        Club club=loginUser.getClub();
        ClubLoginVO clubLoginVO=new ClubLoginVO(jwt,club.getId(),club.getName(),club.getIcon());
        return ResponseResult.okResult(clubLoginVO);
    }
    @GetMapping("/logout")
    public ResponseResult logout(){
            Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
            LoginClubDetails loginClubDetails= (LoginClubDetails) authentication.getPrincipal();
            String clubId=loginClubDetails.getClub().getAccount();
            redisCache.deleteObject(clubId);
            return ResponseResult.okResult();

    }
}
